/*
	Copyright 2007-2010 Petr Ohlidal

	This file is a part of GrobMaker

	GrobMaker is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	GrobMaker is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with GrobMaker.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "FileList.hpp"
#include "../Exception.hpp"
#include "../Images/Image.hpp"

namespace GrobMaker{

int FileList::listDir(const fs::path& dirName, std::list<FileInfo>& files){
	fs::directory_iterator it;
	try{
		it = fs::directory_iterator(dirName);
	}
	catch(fs::filesystem_error e){
		std::stringstream msg;
		msg<<"listDir(): Error reading directory '"<<dirName<<"'.\nDetails:\n"<<e.what();
		throw Exception(msg);
	}
	int noFiles=0;
	while( it!=fs::directory_iterator() ){
		files.push_back(FileInfo(it->path()));
		it++;
		noFiles++;
	}
	return noFiles;
}

bool FileList::sortFileInfoByIndex( const FileInfo& a, const FileInfo& b ){
	if(a.index==FileInfo::noIndex){
		return false;
	}
	else if(b.index==FileInfo::noIndex){
		return true;
	}
	else{
		return a.index<b.index;
	}
}

std::string FileList::fileListToString(std::list<FileInfo>& files, std::string bullet, std::string separator){
	std::stringstream ss;
	for(std::list<FileInfo>::iterator it=files.begin();
		it!=files.end();
		it++){
		fs::path p = it->entry.path();
		ss<<bullet<<p.filename()<<" ("<<it->index<<")"<<separator;
	}
	return ss.str();
}

int FileList::removeUnindexed(std::list<FileInfo>& files){
	int noRemoved=0;
	std::list<FileInfo>::iterator it = files.begin();
	while(it!=files.end()){
		if( it->index==FileInfo::noIndex ){
			it=files.erase(it);
			noRemoved++;
		}
		else{
			it++;
		}
	}
	return noRemoved;
}

int FileList::removeNonImageFiles(std::list<FileInfo>& files){
	std::list<FileInfo>::iterator it = files.begin();
	int noDeleted=0;
	while(it!=files.end()){
		fs::path p = it->entry.path();
		if( Image::resolveExtension(p) ){
			it++;
		}
		else{
			it=files.erase(it);
			noDeleted++;
		}
	}
	return noDeleted;
}

} // namespace GrobMaker
